package com.yunji.web.system;

import com.yunji.common.annotation.Log;
import com.yunji.common.base.BaseController;
import com.yunji.common.base.response.Response;
import com.yunji.common.base.response.ResponseHelper;
import com.yunji.common.constant.UserCode;
import com.yunji.common.enums.common.BusinessType;
import com.yunji.common.model.domain.SysDeptDO;
import com.yunji.common.utils.StringUtils;
import com.yunji.system.context.SystemContext;
import com.yunji.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 部门信息
 *
 * @author ruoyi
 */
@Api(tags = "部门信息")
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @ApiOperation("获取部门列表")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public Response<List<SysDeptDO>> list(SysDeptDO dept) {
        List<SysDeptDO> depts = deptService.selectDeptList(dept);
        return ResponseHelper.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @ApiOperation("查询部门列表(排除节点)")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public Response<List<SysDeptDO>> excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDeptDO> depts = deptService.selectDeptList(new SysDeptDO());
        depts.removeIf(d -> d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + ""));
        return ResponseHelper.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @ApiOperation("根据部门编号获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public Response<SysDeptDO> getInfo(@PathVariable Long deptId) {
        deptService.checkDeptDataScope(deptId);
        return ResponseHelper.success(deptService.selectDeptById(deptId));
    }

    /**
     * 新增部门
     */
    @ApiOperation("新增部门")
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public Response<Long> add(@Validated @RequestBody SysDeptDO dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return ResponseHelper.failure("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SystemContext.getUsername());
        Assert.isTrue(deptService.insertDept(dept) > 0, "添加失败");
        return ResponseHelper.success(dept.getDeptId());
    }

    /**
     * 修改部门
     */
    @ApiOperation("修改部门")
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public Response<String> edit(@Validated @RequestBody SysDeptDO dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return ResponseHelper.failure("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return ResponseHelper.failure("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserCode.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return ResponseHelper.failure("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SystemContext.getUsername());
        Assert.isTrue(deptService.updateDept(dept) > 0, "修改失败");
        return ResponseHelper.success();
    }

    /**
     * 删除部门
     */
    @ApiOperation("删除部门")
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public Response<String> remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return ResponseHelper.failure("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return ResponseHelper.failure("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        Assert.isTrue(deptService.deleteDeptById(deptId) > 0, "删除失败");
        return ResponseHelper.success();
    }
}
